package com.ams.studio.xml;


import org.dom4j.Node;

import java.util.List;

/**

 * Created by zhongyl on 2016-05-25.

 */

public class XmlLoopContext {
    private List<Node> nodes;
    private int index = -1;
    private XmlHelper helper;

    XmlLoopContext(XmlHelper helper, List<Node> nodes) {
        this.helper = helper;
        this.nodes = nodes;
    }

    public XmlHelper getHelper() {
        return helper;
    }

    public boolean next() {
        index++;
        return !end();
    }

    public String getChildNodeValue(String subXPath) {
        if (end() || !hasCallNext()) {
            throw new IllegalArgumentException("context不可用");
        }
        Node childNode = currentNode().selectSingleNode(subXPath);
        if (childNode != null) {
            String text = childNode.getText();
            return text == null ? text : text.trim();
        } else {
            return null;
        }
    }

    public String getChildNodeAttributeValue(String subXPath, String attribute) {
        return getChildNodeValue(subXPath + "/@" + attribute);
    }

    public XmlNodeContext toNodeContext() {
        return new XmlNodeContext(helper, currentNode());
    }

    public String getCurrentNodeValue() {
        if (end() || !hasCallNext()) {
            throw new IllegalArgumentException("context不可用");
        }
        return currentNode().getText();
    }

    public String getCurrentNodeName() {
        if (end() || !hasCallNext()) {
            throw new IllegalArgumentException("context不可用");
        }
        return currentNode().getName();
    }

    Node currentNode() {
        return nodes.get(index);
    }

    private boolean end() {
        return nodes == null || index >= nodes.size();
    }

    private boolean hasCallNext() {
        return index >= 0;
    }

}
